﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Data.Model;
using NHibernate.Criterion;
using System.Collections.Generic;
using ZLCMS.Data.Common;
using NHibernate;

namespace ZLCMS.Web.Example
{
    public partial class DocListTemplate : System.Web.UI.Page
    {
        private string _kind = "Test";//对应的TREEDEF的分类

        protected TreeDef _treeDb;//当前分类

        protected void Page_Load(object sender, EventArgs e)
        {
            using (ISession iNHSession = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                if (!string.IsNullOrEmpty(Request["tid"]))
                {
                    _treeDb = iNHSession.CreateCriteria<TreeDef>().Add(Expression.Eq("Kind", _kind)).Add(Expression.Eq("Id", int.Parse(Request["tid"]))).UniqueResult<TreeDef>();
                }

                //无传入tid，或者传入数据错误
                if (_treeDb == null)
                {
                    // 获取当前KIND的根节点
                    _treeDb = iNHSession.CreateCriteria<TreeDef>().Add(Expression.Eq("Kind", _kind)).Add(Expression.Eq("Parent", 0)).UniqueResult<TreeDef>(); 
                }

                //仍然没有数据跳转首页
                if (_treeDb == null)
                {
                    Response.Redirect("~/");
                }

                int index = anp_list.CurrentPageIndex;
                int currentPageIndex = string.IsNullOrEmpty(Request[anp_list.UrlPageIndexName]) ? 1 : int.Parse(Request[anp_list.UrlPageIndexName]);
                anp_list.PageSize = string.IsNullOrEmpty(Request["pagen"]) ? 8 : int.Parse(Request["pagen"]);

                BindList(iNHSession, currentPageIndex, anp_list.PageSize);
            }
        }

        private void BindList(ISession iNHSession, int pageIndex, int pageSize)
        {
            string whereString = string.Format(" from DocInfo p, TreeDef t where p.TypeId = t.Id and t.Prefix like '%" + _treeDb.Prefix + "%'");

            string countString = " select count(*) " + whereString;

            anp_list.RecordCount = Convert.ToInt32(iNHSession.CreateQuery(countString).UniqueResult());

            string dataString = " select p " + whereString + " order by p.TypeId, p.UpdateDate";

            rp_product.DataSource = iNHSession.CreateQuery(dataString).SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize).List();

            rp_product.DataBind();

        }
    }
}
